<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n'
import { useIcon } from '@/hooks/web/useIcon'
import { reactive, watch, PropType, ref } from 'vue'
import { clientSelect, sendIndex, paymentAdd } from '@/api/common'

import {
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElButton,
  ElTable,
  ElTableColumn,
  ElMessageBox,
  ElInput,
  ElMessage,
  ElDivider,
  ElPagination,
  ElDialog
} from 'element-plus'
import { useCache } from '@/hooks/web/useCache'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useRouter } from 'vue-router'

const { push } = useRouter()
const { emitter } = useEmitt()
const { t } = useI18n()
const addIcon = useIcon({ icon: 'gala:add' })
const delIcon = useIcon({ icon: 'material-symbols:delete-outline' })
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<TableData>>,
    default: () => null
  }
})
watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
  }
)

// 表单对应的字段（绑定到输入框以及选择框俄字段）
const searchTimes: any = ref('')
const form: any = reactive({
  relatedCustomers: '' //关联客户
})

// 分页数据
let currentPage: any = ref(1)
let pageSize: any = ref(10)
let total: any = ref(0)

const handleSizeChange = (ev) => {
  pageSize.value = ev
  toSearch()
}
const handleCurrentChange = (ev) => {
  currentPage.value = ev
  toSearch()
}
// 表格数据
const tableData: any = reactive([])

// 弹窗数据
const yue: any = ref(0)
const payMoney: any = ref(0)
const shoukuan: any = ref(0)
const receiptMoney: any = ref(0)
const popShow = ref(false)
const popData: any = ref([])
const payTime: any = ref('')
const numInput = (ev, index) => {
  let item: any = popData.value[index]
  if (ev >= Number(item.pending_receive)) {
    popData.value[index].getMoney = Number(item.pending_receive)
  }
  shoukuan.value = 0
  popData.value.forEach((litem) => {
    shoukuan.value += Number(litem.getMoney ? litem.getMoney : 0)
  })
}

// 表格实例
const multipleTable: any = ref(null)
// 打开弹窗
const showPopFn = () => {
  console.log('----选择的数据---', multipleTable.value.getSelectionRows())
  popData.value.length = 0
  if (multipleTable.value.getSelectionRows().length > 0) {
    multipleTable.value.getSelectionRows().forEach((item) => {
      receiptMoney.value += Number(item.pending_receive ? item.pending_receive : 0)
      popData.value.push(item)
    })
  }
  if (popData.value.length <= 0) {
    ElMessage.error('请先选择数据')
    return
  }
  receiptMoney.value = 0
  popShow.value = true
}
// 取消销账
const concalAdd = () => {
  popShow.value = false
  payTime.value = ''
  shoukuan.value = 0
  receiptMoney.value = 0
  popData.value.length = 0
}
// 确认销账
const confirmAdd = async () => {
  let listArr: any = []
  let check: any = false
  for (let i = 0; i < popData.value.length; i++) {
    let item = popData.value[i]
    if (item.getMoney > 0) {
      listArr.push({
        id: item.id,
        money: item.getMoney
      })
    } else {
      ElMessage.error(`单号 ${item.purchase_no} 的收款金额为0或空，无法提交`)
      check = true
      break
    }
  }
  if (check) return
  let res: any = await paymentAdd({
    item: 'deliver',
    client_code: form.relatedCustomers,
    list: listArr,
    paytime: payTime.value,
    money: payMoney.value,
    receipt_money: receiptMoney.value
  })
  if (res && res.code == 1) {
    popShow.value = false
    payTime.value = ''
    popData.value.length = 0
    console.log('---新增采购单付款记录---', res)
    emitter.emit('getList', 'add')
    setTimeout(() => {
      push('/financialModule/DeliveryNotePaymentNote')
    }, 300)
  }
}
// 全选数据
const selectAll = (ev) => {
  console.log('---全选数据---', ev)
}
// 选择某条数据
const rowSelect = (ev, row) => {
  console.log('---选择某条数据---', ev, row)
}
// 删除某条数据
const removeSelectItem = (row: any, index: any) => {
  popData.value.splice(index, 1)
  multipleTable.value.toggleRowSelection(row, false)
}
// 选择时间
const timeChange = (ev) => {
  console.log('---ev----', ev, searchTimes.value)
}

const { wsCache } = useCache()
const getToken = wsCache.get('userInfo') ? wsCache.get('userInfo').token : ''

//客户号
const relatedCustomersArr: any = reactive([])
const getClientSelect = async () => {
  let res: any = await clientSelect({})
  res.data.list.forEach((item) => {
    relatedCustomersArr.push({
      label: item.code,
      value: item.code,
      money: item.money
    })
  })
}
getClientSelect()
const changeKhCode = (ev) => {
  console.log('---选择客户---', ev)
  for (let i = 0; i < relatedCustomersArr.length; i++) {
    let item = relatedCustomersArr[i]
    if (item.value == ev) {
      yue.value = item.money
      break
    }
  }
  popData.value.length = 0
  tableData.length = 0
}

// 搜索查询
const toSearch = () => {
  if (!form.relatedCustomers) {
    ElMessage.error('请选择客户号')
    return
  }
  if (!searchTimes.value[0]) {
    ElMessage.error('请选择时间')
    return
  }
  tableData.length = 0
  sendIndexFn()
}
// 重置搜索
const resetSearch = () => {
  form.relatedCustomers = ''
  searchTimes.value = ''
  tableData.length = 0
  currentPage.value = 1
  pageSize.value = 10
}

// 根据条件查询
const sendIndexFn = async () => {
  let res: any = await sendIndex({
    limit: pageSize.value,
    page: currentPage.value,
    filter: `{"client_code":"${form.relatedCustomers}","enacttime":"${searchTimes.value[0]} - ${searchTimes.value[1]}"}`,
    op: `{"client_code":"=","enacttime":"RANGE"}`
  })

  console.log('---搜索---', res)
  if (res && res.code == 1 && res.data.data && res.data.data.length > 0) {
    total.value = res.data.total
    res.data.data.forEach((item) => {
      let time = item.enacttime
      const date = new Date(time * 1000)
      var Y = date.getFullYear()
      var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      item.enacttime = `${Y}-${M}-${D}`
      item.getMoney = 0
      tableData.push(item)
    })
  }
}

watch(form, (newVal, oldVal) => {})

defineExpose({
  getFormData: () => {
    return form
  },
  getRlus: () => {
    return ruleFormRef
  }
})
</script>

<template>
  <ElForm :model="form" ref="ruleFormRef" label-width="auto">
    <ElRow>
      <ElCol :span="6">
        <ElFormItem label-width="100px" prop="relatedCustomers" label="客户号">
          <ElSelect
            @change="changeKhCode"
            v-model="form.relatedCustomers"
            filterable
            clearable
            :placeholder="t('common.inputText')"
          >
            <ElOption
              v-for="item in relatedCustomersArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="5">
        <ElFormItem label-width="50px" label="时间">
          <ElDatePicker
            v-model="searchTimes"
            @change="timeChange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            size="default"
            value-format="YYYY-MM-DD"
          />
        </ElFormItem>
      </ElCol>
      <ElCol :offset="1" :span="6">
        <ElButton type="primary" @click="toSearch">搜索</ElButton>
        <ElButton @click="resetSearch">重置</ElButton>
      </ElCol>
    </ElRow>
    <ElDivider />
    <ElRow>
      <ElCol :span="24">
        <ElButton type="primary" @click="showPopFn">生成收款单</ElButton>
      </ElCol>
      <div class="mt" style="width: 100%; margin-top: 20px"></div>
      <ElCol :span="24">
        <ElTable
          :data="tableData"
          style="width: 100%"
          ref="multipleTable"
          @select="rowSelect"
          @select-all="selectAll"
          row-key="id"
        >
          <ElTableColumn type="selection" reserve-selection width="55" />
          <ElTableColumn prop="id" label="编号" />
          <ElTableColumn prop="waybill" label="单号" />
          <ElTableColumn prop="enacttime" label="日期" />
          <ElTableColumn prop="servicefee" label="应付款金额" />
        </ElTable>
      </ElCol>
      <div class="mt" style="width: 100%; margin-top: 20px"></div>
      <ElCol :span="24">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          layout="sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </ElCol>
    </ElRow>
  </ElForm>

  <ElDialog title="新增采购单付款单" v-model="popShow">
    <div class="fx--sb">
      <div class="dhInput fxy--center">
        <span>客户余额：</span>
        <ElInput v-model="yue" disabled placeholder="客户余额" />
      </div>
      <div class="dhInput fxy--center">
        <span>客户支付金额：</span>
        <ElInput v-model="payMoney" placeholder="客户支付金额" />
      </div>
    </div>
    <div class="fx--sb">
      <div class="dhInput fxy--center">
        <span>总应付款金额：</span>
        <ElInput v-model="receiptMoney" disabled placeholder="请输入付款金额" />
      </div>
      <div class="dhInput fxy--center">
        <span>实际付款金额：</span>
        <ElInput v-model="shoukuan" disabled placeholder="请输入付款金额" />
      </div>
      <div class="dhInput fxy--center">
        <span>付款时间：</span>
        <ElDatePicker
          v-model="payTime"
          type="date"
          placeholder="请选择付款时间"
          value-format="YYYY-MM-DD"
          :shortcuts="[
            {
              text: '今天',
              value: new Date()
            }
          ]"
        />
      </div>
    </div>

    <div class="tkTable">
      <ElTable :data="popData" stripe>
        <ElTableColumn prop="purchase_no" label="单号" />
        <ElTableColumn prop="servicefee" label="应付款金额" />
        <ElTableColumn prop="getMoney" label="实际付款金额">
          <template #default="scope">
            <ElInput
              v-model="scope.row.getMoney"
              :disabled="Number(scope.row.servicefee) <= 0"
              @input="
                (ev) => {
                  numInput(ev, scope.$index)
                }
              "
            />
          </template>
        </ElTableColumn>
        <ElTableColumn width="100px" label="操作">
          <template #default="scope">
            <ElButton
              type="primary"
              circle
              :icon="delIcon"
              @click="removeSelectItem(scope.row, scope.$index)"
            />
          </template>
        </ElTableColumn>
      </ElTable>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="concalAdd">取消</ElButton>
        <ElButton type="primary" @click="confirmAdd"> 确认 </ElButton>
      </span>
    </template>
  </ElDialog>
</template>
<style scoped lang="less">
.fxy--center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.fx--sb {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.dhInput {
  width: 30%;
  margin-bottom: 30px;
  span {
    width: 160px;
  }
}
.listForItem {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .el-col:nth-of-type(2) {
    font-size: var(--el-form-label-font-size);
    padding: 0 15px;
  }
  .el-col:nth-of-type(1) {
    padding-right: 15px;
  }
  .el-col:nth-of-type(6) {
    padding-left: 15px;
  }
  .el-divider--horizontal {
    margin: 0;
  }
  .el-form-item--default {
    margin-bottom: 0;
  }
}
</style>
